package com.example.readerapp.myandserver.util;

import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;

import java.io.IOException;

public class MediaPlayUtil
{
    String path;
    MediaPlayer mediaPlayer;
    public MediaPlayUtil(String path) throws IOException
    {
        this.path=path;
        mediaPlayer=new MediaPlayer();
        mediaPlayer.setDataSource(path);

    }
    public  void startPlay(MediaPlayer.OnCompletionListener onCompletionListener,float speed) throws Exception
    {

        mediaPlayer.prepare();

        //设置播放速度
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            PlaybackParams params=mediaPlayer.getPlaybackParams();
            params.setSpeed(speed);
            mediaPlayer.setPlaybackParams(params);
        }


        mediaPlayer.start();
        //监听音乐是否播放完毕
        mediaPlayer.setOnCompletionListener(onCompletionListener);
    }
    public void pausePlay()
    {
        mediaPlayer.pause();
    }
    public void continuePlay(float speed)
    {
        //设置播放速度
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            PlaybackParams params=mediaPlayer.getPlaybackParams();
            params.setSpeed(speed);
            mediaPlayer.setPlaybackParams(params);
        }
        mediaPlayer.start();
    }
    public void stopPlay()
    {
        try
        {
            mediaPlayer.stop();
        }catch (Exception e)
        {
            System.out.println("暂停播放异常:"+e.toString());
        }
    }
}
